using System;
using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Text;

namespace Pricom.Scripting
{
  public class Script
  {
    public void Add(string scriptEvent, string source)
    {
      CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp"); 
      CompilerParameters cp = new CompilerParameters();
      cp.GenerateExecutable = false;
      cp.GenerateInMemory = true;
      cp.ReferencedAssemblies.Add("system.dll");
      cp.ReferencedAssemblies.Add("pricom.exe");
      //cp.ReferencedAssemblies.Add("system.windows.forms.dll");
      string src = "using Pricom.Scripting; "+
       "class EventHandlerClass" +
       "{" +
       "public static void " + scriptEvent + "(object[] param)" +
       "{" +
       source +
       "}" +
       "}";
      CompilerResults results = compiler.CompileAssemblyFromSource(cp, src);
      //foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
      // MessageBox.Show(ce.ErrorText); 

      if (results.Errors.HasErrors)
      {
        //if (results.Errors[0].ErrorNumber == "CS0029")
        //  return StringEval("Invoke(delegate { " + expr + "; })");
        //return results.Errors[0].ErrorText;
      }
      else
      {
        Assembly assm = results.CompiledAssembly;
        Type target = assm.GetType("EventHandlerClass");
        MethodInfo method = target.GetMethod(scriptEvent);
        codes.Add(scriptEvent, method);
        //object result = method.Invoke(null, null);
        //return result == null ? null : result.ToString();
      }
    }

    private Dictionary<string, MethodInfo> codes = new Dictionary<string, MethodInfo>();

    public void RunScript(string scriptEvent, object[] param)
    {
      MethodInfo method = codes[scriptEvent];
      method.Invoke(null, new object[] { param });
    }
    public void Test()
    {
      Add("OnNickClicked", "MessageBox.Show(\"ok\");");
      Add("OnValamiClicked", "MessageBox.Show(param[0].ToString());");
    }
    public void Test2()
    {
      RunScript("OnValamiClicked", new object[] { "Orulunk, Vincent!" } );
    }
  }
}
